package com.ruoyi.cm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.base.domain.BaseBsZd;
import com.ruoyi.base.domain.vo.BaseBsZdVo;
import com.ruoyi.base.mapper.BaseBsZdMapper;
import com.ruoyi.cm.domain.CmBaSettleDeductDetail;
import com.ruoyi.cm.domain.CmPeriodMeasurement;
import com.ruoyi.cm.domain.vo.CmBsContractInfoMilestoneVo;
import com.ruoyi.cm.mapper.CmBaSettleDeductDetailMapper;
import com.ruoyi.cm.mapper.CmBsContractInfoMilestoneMapper;
import com.ruoyi.cm.mapper.CmPeriodMeasurementMapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.mapper.SysDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.cm.domain.bo.CmBsQsBo;
import com.ruoyi.cm.domain.vo.CmBsQsVo;
import com.ruoyi.cm.domain.CmBsQs;
import com.ruoyi.cm.mapper.CmBsQsMapper;
import com.ruoyi.cm.service.ICmBsQsService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 期数管理Service业务层处理
 *
 * @author zyb
 * @date 2024-09-24
 */
@RequiredArgsConstructor
@Service
public class CmBsQsServiceImpl implements ICmBsQsService {

    private final CmBsQsMapper baseMapper;
    private final CmPeriodMeasurementMapper measurementMapper;
    private final CmBaSettleDeductDetailMapper deductDetailMapper;
    private final BaseBsZdMapper zdMapper;
    private final SysDeptMapper deptMapper;
//    private final CmBsContractInfoMilestoneMapper milestoneMapper;

    /**
     * 查询期数管理
     */
    @Override
    public CmBsQsVo queryById(Long qsId){
        return baseMapper.selectVoById(qsId);
    }

    /**
     * 查询期数管理列表
     */
    @Override
    public TableDataInfo<CmBsQsVo> queryPageList(CmBsQsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CmBsQs> lqw = buildQueryWrapper(bo);
        Page<CmBsQsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //查询里程碑名称；
//        Set<Long> miles = result.getRecords().stream().map(CmBsQsVo::getContractMilestone).collect(Collectors.toSet());
//        if(CollUtil.isNotEmpty(miles)){
//            List<CmBsContractInfoMilestoneVo> milestoneVos = milestoneMapper.selectVoBatchIds(miles);
//            Map<Long, BigDecimal> mileMap = milestoneVos.stream().collect(Collectors.toMap(CmBsContractInfoMilestoneVo::getId, CmBsContractInfoMilestoneVo::getKgyfkbl));
//            result.getRecords().forEach(e->e.setContractMilestoneName(mileMap.get(e.getContractMilestone())));
//        }

        //设置当前登录用户所属单位；
        SysDept sysDept = deptMapper.selectVoById(LoginHelper.getDeptId());
        result.getRecords().forEach(e->{
            e.setDeptType(sysDept.getDeptType());
            e.setHasJl(0);
        });
        //查询是否计量过；
        Integer type = bo.getJlType();
        Long zdId = bo.getZdId();
        if (type != null && zdId != null) {
            List<CmBsQsVo> records = result.getRecords();
            Set<Long> qsIds = records.stream().map(CmBsQsVo::getQsId).collect(Collectors.toSet());
            if(CollUtil.isNotEmpty(qsIds)){
                //1.中间计量
                if (type == 1 ) {
                    List<CmPeriodMeasurement> measurements = measurementMapper.selectList(new LambdaQueryWrapper<CmPeriodMeasurement>().
                        eq(CmPeriodMeasurement::getZdId, zdId).in(CmPeriodMeasurement::getQsId, qsIds));
                    if (CollUtil.isNotEmpty(measurements)) {
                        Map<Long, List<CmPeriodMeasurement>> qsIdPeriodMap = measurements.stream().collect(Collectors.groupingBy(CmPeriodMeasurement::getQsId));
                        for (CmBsQsVo qsVo : records) {
                            List<CmPeriodMeasurement> qsPeriods = qsIdPeriodMap.get(qsVo.getQsId());
                            if (CollUtil.isNotEmpty(qsPeriods)) {
                                for (CmPeriodMeasurement p : qsPeriods) {
                                    BigDecimal totalPrice = p.getTotalPrice();
                                    if (totalPrice != null && totalPrice.compareTo(BigDecimal.ZERO) > 0) {
                                        qsVo.setHasJl(1);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    //其他计量
                } else if (type == 2 ) {
                    List<CmBaSettleDeductDetail> deductDetails = deductDetailMapper.selectList(new LambdaQueryWrapper<CmBaSettleDeductDetail>().
                        eq(CmBaSettleDeductDetail::getZdId, zdId).in(CmBaSettleDeductDetail::getQsId, qsIds));
                    if (CollUtil.isNotEmpty(deductDetails)) {
                        Map<Long, List<CmBaSettleDeductDetail>> qsDeductMap = deductDetails.stream().collect(Collectors.groupingBy(CmBaSettleDeductDetail::getQsId));
                        for (CmBsQsVo qsVo : records) {
                            List<CmBaSettleDeductDetail> details = qsDeductMap.get(qsVo.getQsId());
                            if (CollUtil.isNotEmpty(details)) {
                                qsVo.setHasJl(1);
                            }
                        }
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询期数管理列表
     */
    @Override
    public List<CmBsQsVo> queryList(CmBsQsBo bo) {
        LambdaQueryWrapper<CmBsQs> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CmBsQs> buildQueryWrapper(CmBsQsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CmBsQs> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getContractMilestone() != null, CmBsQs::getContractMilestone, bo.getContractMilestone());
        lqw.eq(bo.getBdId() != null, CmBsQs::getBdId, bo.getBdId());
        lqw.eq(bo.getSettleIndex() != null, CmBsQs::getSettleIndex, bo.getSettleIndex());
        lqw.like(StringUtils.isNotBlank(bo.getSettleName()), CmBsQs::getSettleName, bo.getSettleName());
        lqw.eq(bo.getSettleBeginDate() != null, CmBsQs::getSettleBeginDate, bo.getSettleBeginDate());
        lqw.eq(bo.getSettleEndDate() != null, CmBsQs::getSettleEndDate, bo.getSettleEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getPayMode()), CmBsQs::getPayMode, bo.getPayMode());
        lqw.eq(bo.getSettleDate() != null, CmBsQs::getSettleDate, bo.getSettleDate());
        lqw.eq(bo.getPayDate() != null, CmBsQs::getPayDate, bo.getPayDate());
        lqw.eq(StringUtils.isNotBlank(bo.getZfsqyj()), CmBsQs::getZfsqyj, bo.getZfsqyj());
        return lqw;
    }

    /**
     * 新增期数管理
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(CmBsQsBo bo) {
        CmBsQs add = BeanUtil.toBean(bo, CmBsQs.class);
        validEntityBeforeSave(add);
        //保存之前校验当前期数是否已过期；
        CmBsQs qs = getQs(bo.getBdId());
        if (bo.getSettleIndex() != qs.getSettleIndex()) {
            return false;
        }
        //修改其他期数当前期标志；
        updateCurrent(bo);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setQsId(add.getQsId());
        }
        return flag;
    }

    /**
     * 修改期数管理
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(CmBsQsBo bo) {
        CmBsQs update = BeanUtil.toBean(bo, CmBsQs.class);
        validEntityBeforeSave(update);
        //修改其他期数当前期标志；
        updateCurrent(bo);
        return baseMapper.updateById(update) > 0;
    }

    //修改其他期数当前期标志；
    private void updateCurrent(CmBsQsBo bo) {
        //如果本期设为当前期标志1，修改其他期次的当前期标志为0；
        if (bo.getCurrentFlag() != null && bo.getCurrentFlag() == 1) {
            List<CmBsQs> qsList = baseMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId, bo.getBdId()));
            if (CollUtil.isNotEmpty(qsList)) {
                qsList.forEach(e -> e.setCurrentFlag(0));
                baseMapper.updateBatchById(qsList);
            }
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CmBsQs entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除期数管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public CmBsQs getQs(Long bdId) {
        LambdaQueryWrapper<CmBsQs> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmBsQs::getBdId,bdId);
        wrapper.orderByDesc(CmBsQs::getSettleIndex);
        List<CmBsQs> cmBsQs = baseMapper.selectList(wrapper);
        if(CollUtil.isNotEmpty(cmBsQs)){
            CmBsQs qs = cmBsQs.get(0);
            qs.setSettleIndex(qs.getSettleIndex()+1);
            return qs;
        }
        CmBsQs qs = new CmBsQs();
        qs.setSettleIndex(1);
        return qs;
    }

    @Override
    public List<CmBsQsVo> qsList(CmBsQsBo bo) {
        List<CmBsQsVo> voList = new ArrayList<>();
        Long bdId = bo.getBdId();
        if (bdId == null) {
            if (bo.getZdId() == null) {
                return voList;
            }
            BaseBsZdVo baseBsZdVo = zdMapper.selectVoById(bo.getZdId());
            if (baseBsZdVo.getBdId() == null) {
                return voList;
            }
            bdId = baseBsZdVo.getBdId();
        }
        return baseMapper.selectVoList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId, bdId));
    }
}
